/* 工厂任务拓展 */
import { compare, isInArray } from "@/utils"
import { FactoryConstantList } from "./factory_constant"

export default class factoryExtension extends StructureFactory {
    public ManageMisson():void{
        if (!this.room.memory.factory) this.room.memory.factory = {}
        if (!this.room.memory.Misson['Structure']) this.room.memory.Misson['Structure'] = []
        /* 任务挂载监控 */
        this.BasicFactory() /* 基础物质合成  需要工厂的work为'basic */
        var allmyTask = []
        for (var task of this.room.memory.Misson['Structure'])
        {
            if (!task.structure) continue
            if (isInArray(task.structure,this.id))
            {
                allmyTask.push(task)
            }
        }
        /* 按照优先级排序 */
        if (allmyTask.length <= 0)
        {
            return
        }
        else if (allmyTask.length >= 1)
            allmyTask.sort(compare('level'))
        /* 处理任务 */
        let thisTask = allmyTask[0]
        // if (this.room.name == 'E49S53')console.log(thisTask)
        switch (thisTask.name){
            case "工厂加工":{this.FactoryProduct(thisTask);break}
        }
    }

    /* 工厂加工函数 */
    public FactoryProduct(misson:MissionModel):void{
        if (!global.Gtime) global.Gtime = {}
        if (!global.Gtime[this.room.name])global.Gtime[this.room.name] = Game.time
        if((Game.time - global.Gtime[this.room.name]) % 10) return
        if (this.cooldown) return 
        if (misson.data.level > this.level){this.room.DeleteMisson(misson.id);return}
        if(!misson.data.state) misson.data.state = 1 
        var storage_ = global.Stru[this.room.name]['storage'] as StructureStorage
        if (!storage_) return
        if (misson.data.state == 1)
        {
            /* 1阶段负责凑齐原料 */
            // 获取合成数量
            var disNum = misson.data.num
            /* 获取合成数量和一次加工最小数量比值 */
            var mult = Math.ceil(disNum/FactoryConstantList[this.room.memory.factory.work][misson.data.disResource].num)   // 倍数 500
            /* 加工化合物的底物信息 */
            var message = FactoryConstantList[this.room.memory.factory.work][misson.data.disResource].raw
            for (var i in message)
            {
                var rawmult = Math.ceil(FactoryConstantList[this.room.memory.factory.work][misson.data.disResource].raw[i]/FactoryConstantList[this.room.memory.factory.work][misson.data.disResource].num) // 5
                if(this.store.getUsedCapacity(i as ResourceConstant) <  disNum*rawmult)   
                {
                    /* 仓库有资源就直接发布搬运物流任务 */
                    if (storage_.store.getUsedCapacity(i as ResourceConstant) + this.store.getUsedCapacity(i as ResourceConstant) >= disNum*rawmult)
                    {
                        if (this.room.RoleMissonNum('manage','物流运输')>0) return
                        var carryTask = this.room.Public_Carry({'manage':{num:1,bind:[]}},40,this.room.name,storage_.pos.x,storage_.pos.y,this.room.name,this.pos.x,this.pos.y,i as ResourceConstant,disNum*rawmult-this.store.getUsedCapacity(i as ResourceConstant)) 
                        this.room.AddMisson(carryTask)
                        return
                    }
                    else
                    {
                        /* 寻找物流运输 */
                        if (i == 'energy') return       // 能量除外
                        // console.log(disNum*rawmult-this.store.getUsedCapacity(i as ResourceConstant))
                        var result = this.room.Resource_Dispatch(i as ResourceConstant,disNum*rawmult-this.store.getUsedCapacity(i as ResourceConstant))
                        if (result == false && isInArray(['L','H','O','U','K','Z','X','G'],i))
                        {
                            var terminal_ = global.Stru[this.room.name]['terminal'] as StructureTerminal
                            if (!terminal_) return
                            /* 如果还没有就直接挂单买啦 */
                            if (storage_.store.getUsedCapacity(i as ResourceConstant) +terminal_.store.getUsedCapacity(i as ResourceConstant) < disNum*rawmult -this.store.getUsedCapacity(i as ResourceConstant))
                            this.room.Deal_Resource(i as ResourceConstant,disNum*rawmult-this.store.getUsedCapacity(i as ResourceConstant)+3000,5,30)
                        }
                    }
                    return
                }
            }
            misson.data.state = 2
        }
        else if (misson.data.state == 2)
        {
            var r = this.produce(misson.data.disResource)
            /* 2阶段负责生产 */
            if (r == OK)
            {
                misson.data.num -= FactoryConstantList[this.room.memory.factory.work][misson.data.disResource].num
            }
            else if (r == -6)
            {
                misson.data.state = 1
            }
            if (misson.data.num <= 0)
            {
                misson.data.state = 3
            }
        }
        else if (misson.data.state == 3)
        {
            /* 3阶段负责收工 */
            for (var re in this.store)
            {
                if(this.room.RoleMissonNum('manage','物流运输') <= 0)
                {
                    var carryTask = this.room.Public_Carry({'manage':{num:1,bind:[]}},40,this.room.name,this.pos.x,this.pos.y,this.room.name,storage_.pos.x,storage_.pos.y,re as ResourceConstant,this.store[re]) 
                    this.room.AddMisson(carryTask)
                    return
                }
            }
            if (this.store.getUsedCapacity() <= 0)
            {
                this.room.DeleteMisson(misson.id)
                return
            }
        }

    }

    /* 获取商品加工所需化合物及数量 */
    public GetMaterials(product:CommodityConstant): Record<"energy" | MineralConstant | "G" | DepositConstant | CommodityConstant, number>{
        if (!product) return {} as Record<"energy" | MineralConstant | "G" | DepositConstant | CommodityConstant, number>
        return COMMODITIES[product].components
    }

    /* 生产基础物件 */
    public BasicFactory():void{
        if(this.room.memory.factory.level != 0 || !this.room.memory.factory.work || this.room.memory.factory.work != 'zip') return
        //var basicBar:CommodityConstant[] = ['lemergium_bar','reductant','battery','utrium_bar','keanium_bar','zynthium_bar','oxidant','purifier','purifier']
        if (!this.room.memory.factory.list) this.room.memory.factory.list = ['battery','lemergium_bar','utrium_bar','zynthium_bar','keanium_bar']
        var basicBar:CommodityConstant[] = this.room.memory.factory.list
        var storage_ = global.Stru[this.room.name]['storage'] as StructureStorage
        if (!storage_) return
        for (var Resource of basicBar)
        {
            /* 这里写死，常被20K的各种基础资源 */
            if(storage_.store.getUsedCapacity(Resource) < 20000 && this.room.MissonNum('Structure','工厂加工') <= 0 && this.room.RoleMissonNum('manage','物流运输') <= 0)
            {
                /* 判断有无运输任务 */
                /* 少了就合 多和3000 */
                var disNum = Resource!='battery'?5000:2500          // 一次合5000
                var thisTask:MissionModel=  {
                    name:'工厂加工',
                    delayTick:99999,
                    range:'Structure',
                    structure:[this.id],
                    data:{
                        disResource:Resource,
                        num:disNum,
                        level:0,
                        cType:this.room.memory.factory.work

                    }
                }
                this.room.AddMisson(thisTask)
                return
            }
        }

    }
}